package org.nowcoder.leetcode.BTree;

import java.util.ArrayDeque;
import java.util.Queue;

/**
 * Title  : 513. Find Bottom Left Tree Value
 * Source : https://leetcode.cn/problems/find-bottom-left-tree-value/description/
 * Author : XrazYang
 * Date   : 2023-04-15
 */

public class LeetCode_513 {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int findBottomLeftValue(TreeNode root) {
        Queue<TreeNode> que = new ArrayDeque<>();
        que.offer(root);
        int result = root.val;
        while (!que.isEmpty()) {
            int size = que.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = que.poll();
                if (i == 0) {
                    result = node.val;
                }
                if (node.left != null) {
                    que.offer(node.left);
                }
                if (node.right != null) {
                    que.offer(node.right);
                }
            }
        }
        return result;
    }
}
